package jmu.cze.controller;

import jmu.cze.pojo.Order;
import jmu.cze.service.BookService;
import jmu.cze.utl.ResultUtil;
import jmu.cze.utl.UUIDUtil;
import jmu.cze.vo.PostBookInfo;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class BookController {
    private BookService bookService;

    @Resource(name = "bookServiceImpl")
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/book")
    public String book(Integer ticketTypeID,Model model, HttpSession session){
        model.addAttribute("ticketTypeID",ticketTypeID);
        return "book";
    }

    @PostMapping("/book")
    @ResponseBody
    public String doBook(@RequestBody PostBookInfo postBookInfo, HttpSession session){
        System.out.println(postBookInfo);
        Order order = new Order();
        order.setCustomerID((String) session.getAttribute("id"));
        order.setUseIntegral(0);
        order.setOrderCosts(0.0);
        order.setPaymentStatus("未支付");
        if (bookService.book(order, postBookInfo.getTicketTypeID(), postBookInfo.getPassengers())) {
            return ResultUtil.getNext("payment/"+order.getOrderID(),1);
        }
        return ResultUtil.getResult(false);
    }

    @GetMapping("/payment/{orderID}")
    public String payment(@PathVariable("orderID") int orderID, Model model,HttpSession session){
        model.addAttribute("order", bookService.selectOrderByID(orderID));
        model.addAttribute("airTickets",bookService.selectAirTicketsByOrderID(orderID));

        session.setAttribute("orderID",orderID);
        session.setAttribute("code", UUIDUtil.generateUUID());
        return "payment";
    }

    @PostMapping("/doPayment")
    public String doPayment(int orderID, String code, Model model, HttpSession session){
        model.addAttribute("msg", "支付失败");
        if((int)session.getAttribute("orderID")==orderID
                && ((String)session.getAttribute("code")).equals(code)){
            Order order = bookService.selectOrderByID(orderID);
            order.setPaymentStatus("已支付");
            if(bookService.updateOrder(order)){
                model.addAttribute("msg", "支付成功");
            }
        }
        return "info";
    }
}
